﻿using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
using CloudShot.Core.Interfaces;
using CloudShot.Core.Types;
using CloudShot.Properties;

namespace CloudShot.ImageStorages
{
	public class FileSystemStorage : IImageStorage
	{
        private readonly FileSystemStorageSettingsControl _settingsUIHolder;
		private ISettingsRepository _settingsRepository;

		public Image Logo { get { return Resources.folder; } }

		public string Name { get { return "Local Folder"; } }

		public string Description
		{
			get { return "Image will be saved to local folder and path to image will be copied to clipboard"; }
		}

		public IEnumerable<ImageSaveFormat> SupportedFormats
		{
            get { return new[] { ImageSaveFormat.Png, ImageSaveFormat.Jpg, ImageSaveFormat.Jpeg, ImageSaveFormat.Gif }; }
		}

        #region Settings

        public ImageSaveFormat CurrentImageFormat
        {
            get { return GetSetting<ImageSaveFormat>(); }
            internal set { SetSetting(value); }
        }

        public string FolderToSave
        {
            get
            {
                string folderToSave = GetSetting<string>();

                if (string.IsNullOrEmpty(folderToSave))
                    folderToSave = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyPictures), "CloudShot");

                return folderToSave;
            }
            internal set { SetSetting(value); }
        }

        private T GetSetting<T>([CallerMemberName] string name = "")
        {
            return _settingsRepository.GetSetting<T>(name);
        }

        private void SetSetting<T>(T value, [CallerMemberName] string name = "")
        {
            _settingsRepository.SetSetting(name, value);
        }

        #endregion

		public ISettingsRepository SettingsRepository { get { return _settingsRepository; } }

        public ISettingsUIHolder SettingsUIHolder
        {
            get { return _settingsUIHolder; }
        }

	    public FileSystemStorage()
	    {
            _settingsUIHolder = new FileSystemStorageSettingsControl(this);
	    }

		public void Initialize(ISettingsRepository settingsRepository)
		{
			_settingsRepository = settingsRepository;
		}

		public async Task<ShotInfo> SaveImage(Image image, string shotName, ImageFormat saveImageFormat)
		{
			Directory.CreateDirectory(FolderToSave);//create directory if not exist
			string pathToSave = Path.Combine(FolderToSave, shotName);

			using (var ms = new MemoryStream())
			using (var fs = new FileStream(pathToSave, FileMode.Create))
			{
				image.Save(ms, saveImageFormat);
				ms.WriteTo(fs);
			}

			return new ShotInfo(shotName, pathToSave, image);
		}
	}
}